package com.xca.znb.view;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.xca.znb.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.xca.znb.model.impl.AddGoodsImpl;
import com.xca.znb.presenter.AddGoodsPresenter;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


public class AddGoodsActivity extends AppCompatActivity {

   private BottomSheetDialog bottomSheetDialog;
   private EditText mGoodsNameEdit;
   private Button mSendButton;
   private ImageView mbackbutton , firstImg;
   private TextView goodsType , goodsPrice , goodsUnit , goodsFreight , goodsLocal;
   private ImageButton typeBtn , priceBtn , unitBtn , freightBtn , localBtn  , addPhoto;
   private EditText goodsText ;
   private GridView mShowPhoto ;

   private static final int REQUEST_PICK_IMAGES = 88;
   private static final int PERMISSION_REQUEST_CODE = 666;
   private List<Uri> selectedImages = new ArrayList<>();
   private final String[] imgArray = new String[0];
   private ImageAdapter adapter;

   private static final int PICK_IMAGE_REQUEST = 1;



   //导入presenter
   private AddGoodsPresenter presenter ;
   @SuppressLint("MissingInflatedId")
   @Override
   protected void onCreate(@Nullable Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
//      getWindow().setEnterTransition(new Slide());    // 从下往上滑动效果
      setContentView(R.layout.activity_add_goods);

      mGoodsNameEdit = findViewById(R.id.et_goods_name);
      mSendButton = findViewById(R.id.goods_send);

      goodsType = findViewById(R.id.addGoods_setType) ;
      goodsPrice = findViewById(R.id.addGoods_setPrice) ;
      goodsUnit = findViewById(R.id.addGoods_setUnit) ;
      goodsFreight = findViewById(R.id.addGoods_setFreight) ;
      goodsLocal = findViewById(R.id.addGoods_setLocal) ;

      typeBtn = findViewById(R.id.addGoods_setType_btn);
      priceBtn = findViewById(R.id.addGoods_setPrice_btn) ;
      unitBtn = findViewById(R.id.addGoods_setUnit_btn);
      freightBtn = findViewById(R.id.addGoods_setFreight_btn);
      localBtn = findViewById(R.id.addGoods_setLocal_btn) ;
      addPhoto = findViewById(R.id.publish_goods_addPhoto);

      goodsText = findViewById(R.id.addGoods_setText) ;

      mShowPhoto = findViewById(R.id.rv_goods_photo);

      //缩略图
      firstImg = findViewById(R.id.publish_goods_img);

      AddGoodsImpl addGoods = new AddGoodsImpl(this);
      presenter = new AddGoodsPresenter(addGoods);


      //获取图片路径
      firstImg.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
         }
      });



      adapter = new ImageAdapter();
      mShowPhoto.setAdapter(adapter);

      addPhoto.setOnClickListener(v -> pickImagesFromGallery());

      if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
              != PackageManager.PERMISSION_GRANTED) {
         ActivityCompat.requestPermissions(this,
                 new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                 PERMISSION_REQUEST_CODE);
      }




      typeBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showBottomSheet1();
         }
      });
      priceBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showBottomSheet2();
         }
      });
      unitBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showBottomSheet3();
         }
      });
      freightBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showBottomSheet4();
         }
      });
      localBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            showBottomSheet5();
         }
      });

      mbackbutton=findViewById(R.id.back);

      mbackbutton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            onBackPressed();
         }
      });



      mSendButton.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            //获取货品名称
            String name = mGoodsNameEdit.getText().toString() ;
            if (name.isEmpty()){
               Toast.makeText(AddGoodsActivity.this, "请输入货品名称", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品缩略图路径
            SharedPreferences sharedPreferences1 = getSharedPreferences("publish_firstImg" , Context.MODE_PRIVATE);
            String imgPath = sharedPreferences1.getString("publish_firstImage" , "");
            Uri uri = Uri.parse(imgPath);
            String img1 = saveImageToAppFolder(uri);

            //获取list图片路径
           String[] imgList = new String[selectedImages.size()];
           for (int i=0 ; i<imgList.length ; i++){
              String img =String.valueOf(selectedImages.get(i)) ;
              Uri uri1 = Uri.parse(img);
              String img_l = saveImageToAppFolder(uri1);
              imgList[i] = img_l ;
           }
           Gson gson = new Gson() ;
           String jsonImages = gson.toJson(imgList);
            //Toast.makeText(AddGoodsActivity.this, jsonImages, Toast.LENGTH_SHORT).show();
            //String jsonImages = uriListToJson(selectedImages);
            //获取货品类型
            String type = goodsType.getText().toString();
            if (type.equals("请选择货品分类")){
               Toast.makeText(AddGoodsActivity.this, "请选择货品分类", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品单价
            String num = goodsPrice.getText().toString();
            if (num.equals("请输入货品单价")){
               Toast.makeText(AddGoodsActivity.this, "请输入货品单价", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品单位
            String unit = goodsUnit.getText().toString();
            if (unit.equals("请选择货品单位")){
               Toast.makeText(AddGoodsActivity.this, "请选择货品单位", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品运费
            String freight = goodsFreight.getText().toString();
            if (freight.equals("请设置运费")){
               Toast.makeText(AddGoodsActivity.this, "请设置运费", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品发货地址
            String address = goodsLocal.getText().toString();
            if (address.equals("请选择货品发货地址")){
               Toast.makeText(AddGoodsActivity.this, "请选择货品发货地址", Toast.LENGTH_SHORT).show();
               return;
            }
            //获取货品描述
            String text = goodsText.getText().toString();
            //获取货品发布者\
            SharedPreferences sharedPreferences = getSharedPreferences("loginPhone", Context.MODE_PRIVATE);
            String phone = sharedPreferences.getString("phone" , "");
            String state = "上架中";

            double price = Double.parseDouble(num);


               boolean isAdd = presenter.addGoods(name , img1 , jsonImages , type , price , unit , freight , address , text , phone , state);
               if (isAdd){
                  Toast.makeText(AddGoodsActivity.this, "商品发布成功", Toast.LENGTH_SHORT).show();
                  finish();
               }else {
                  Toast.makeText(AddGoodsActivity.this, "商品发布失败", Toast.LENGTH_SHORT).show();
               }
         }
      });
   }

   // 将Uri列表转换为JSON字符串的方法
   private String uriListToJson(List<Uri> uriList) {
      Gson gson = new Gson();
      return gson.toJson(uriList);
   }

   private void showBottomSheet1() {
      // 如果BottomSheetDialog还未创建，则创建它
//        if (bottomSheetDialog == null) {
      bottomSheetDialog = new BottomSheetDialog(AddGoodsActivity.this);
      bottomSheetDialog.setContentView(R.layout.procurement_goods_type);

      // 找到BottomSheet中的按钮，并设置点击事件
      Button option1 = bottomSheetDialog.findViewById(R.id.goods_option1);
      Button option2 = bottomSheetDialog.findViewById(R.id.goods_option2);
      Button option3 = bottomSheetDialog.findViewById(R.id.goods_option3);
      // 设置按钮点击事件，这里只是示例，实际中可以处理选项的逻辑
      option1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option1.getText().toString();
            goodsType.setText(type);
            // 处理选项1的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
      option2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option2.getText().toString();
            goodsType.setText(type);
            // 处理选项2的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
      option3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option3.getText().toString();
            goodsType.setText(type);
            // 处理选项2的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
//        }

      // 显示BottomSheet
      bottomSheetDialog.show();
   }

   private void showBottomSheet2() {
      // 如果BottomSheetDialog还未创建，则创建它
//        if (bottomSheetDialog == null) {
      bottomSheetDialog = new BottomSheetDialog(AddGoodsActivity.this);
      bottomSheetDialog.setContentView(R.layout.add_goods_price);

      EditText setPrice = bottomSheetDialog.findViewById(R.id.add_goods_money_number);
      ImageButton cancel = bottomSheetDialog.findViewById(R.id.add_goods_cancel);
      Button sure = bottomSheetDialog.findViewById(R.id.add_goods_price_btn) ;
      // 设置按钮点击事件，这里只是示例，实际中可以处理选项的逻辑
      cancel.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // 处理选项1的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
      sure.setOnClickListener(new View.OnClickListener() {
         @SuppressLint("SetTextI18n")
         @Override
         public void onClick(View v) {
            // 处理选项2的点击事件
            String inputPrice = setPrice.getText().toString();
           // double price = Double.parseDouble(inputPrice);,可获取浮点数值
            goodsPrice.setText(inputPrice);
             bottomSheetDialog.dismiss();
         }
      });
//        }

      // 显示BottomSheet
      bottomSheetDialog.show();
   }

   private void showBottomSheet3() {
      // 如果BottomSheetDialog还未创建，则创建它
//        if (bottomSheetDialog == null) {
      bottomSheetDialog = new BottomSheetDialog(AddGoodsActivity.this);
      bottomSheetDialog.setContentView(R.layout.procurement_goods_unit);

      List<Button> buttons = new ArrayList<>();
      buttons.add(bottomSheetDialog.findViewById(R.id.unit1));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit2));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit3));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit4));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit5));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit6));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit7));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit8));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit9));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit10));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit11));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit12));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit13));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit14));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit15));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit16));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit17));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit18));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit19));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit20));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit21));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit22));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit23));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit24));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit25));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit26));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit27));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit28));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit29));
      buttons.add(bottomSheetDialog.findViewById(R.id.unit30));


      // 设置按钮点击事件，这里只是示例，实际中可以处理选项的逻辑
     for (Button button : buttons){
        button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
              String getText = ((Button) v).getText().toString();
              goodsUnit.setText(getText);
              bottomSheetDialog.dismiss();
           }
        });
     }
//        }

      // 显示BottomSheet
      bottomSheetDialog.show();
   }

   private void showBottomSheet4() {
      // 如果BottomSheetDialog还未创建，则创建它
//        if (bottomSheetDialog == null) {
      bottomSheetDialog = new BottomSheetDialog(AddGoodsActivity.this);
      bottomSheetDialog.setContentView(R.layout.goods_freight);

      // 找到BottomSheet中的按钮，并设置点击事件
      Button option1 = bottomSheetDialog.findViewById(R.id.freight_option1);
      Button option2 = bottomSheetDialog.findViewById(R.id.freight_option2);
      Button option3 = bottomSheetDialog.findViewById(R.id.freight_option3);
      // 设置按钮点击事件，这里只是示例，实际中可以处理选项的逻辑
      option1.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option1.getText().toString();
            goodsFreight.setText(type);
            // 处理选项1的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
      option2.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option2.getText().toString();
            goodsFreight.setText(type);
            // 处理选项2的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
      option3.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String type = option3.getText().toString();
            goodsFreight.setText(type);
            // 处理选项2的点击事件
            bottomSheetDialog.dismiss(); // 关闭BottomSheet
         }
      });
//        }

      // 显示BottomSheet
      bottomSheetDialog.show();
   }

   private void showBottomSheet5() {
      bottomSheetDialog = new BottomSheetDialog(AddGoodsActivity.this);
      bottomSheetDialog.setContentView(R.layout.update_user_local);
      EditText UpdateLocal = bottomSheetDialog.findViewById(R.id.update_input_local);
      ImageButton Cancel = bottomSheetDialog.findViewById(R.id.update_local_cancel) ;
      Button Save = bottomSheetDialog.findViewById(R.id.save_new_local_btn) ;

      Cancel.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            bottomSheetDialog.dismiss();
         }
      });
      Save.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String newLocal = UpdateLocal.getText().toString() ;
            goodsLocal.setText(newLocal);
            bottomSheetDialog.dismiss();
         }
      });
      bottomSheetDialog.show();
   }

   private void pickImagesFromGallery() {
      Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      intent.setType("image/*");
      intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); // 允许选择多张图片
      startActivityForResult(intent, REQUEST_PICK_IMAGES);
   }

   @Override
   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
      super.onRequestPermissionsResult(requestCode, permissions, grantResults);
      if (requestCode == PERMISSION_REQUEST_CODE) {
         if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 用户已授权，可以进行图片选择
         } else {
           // Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
         }
      }
   }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      if (requestCode == REQUEST_PICK_IMAGES && resultCode == RESULT_OK) {
         if (data.getClipData() != null) {
            int count = data.getClipData().getItemCount();
            for (int i = 0; i < count; i++) {
               Uri imageUri = data.getClipData().getItemAt(i).getUri();
               //Toast.makeText(this, String.valueOf(imageUri), Toast.LENGTH_SHORT).show();
               selectedImages.add(imageUri);
            }
         } else if (data.getData() != null) {
            Uri imageUri = data.getData();
            //Toast.makeText(this, String.valueOf(imageUri), Toast.LENGTH_SHORT).show();

            selectedImages.add(imageUri);
         }
         adapter.notifyDataSetChanged();
      }

      if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
         Uri selectedImageUri = data.getData();
         String imagePath = selectedImageUri.toString().trim();
         SharedPreferences sharedPreferences = getSharedPreferences("publish_firstImg" , Context.MODE_PRIVATE);
         SharedPreferences.Editor editor = sharedPreferences.edit() ;
         editor.putString("publish_firstImage" , imagePath);
         editor.apply();
         Uri uri = Uri.parse(imagePath);
         firstImg.setImageURI(uri);}


   }

   private String saveImageToAppFolder(Uri imageUri) {
      String savedImagePath = null;

      if (imageUri == null || imageUri.toString().isEmpty()) {
         Log.e("ImageSave", "Invalid image Uri provided");
         return null;
      }

      try {
         File dir_news = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
         if (dir_news == null) {
            Log.e("ImageSave", "Failed to get app's private directory");
            return null;
         }

         if (!dir_news.exists() && !dir_news.mkdirs()) {
            Log.e("ImageSave", "Failed to create directories");
            return null;
         }

         // 新增逻辑：确保文件名唯一
         String imageNameBase = "image_";
         String imageNameExtension = ".jpg";
         File file;
         int counter = 0;
         do {
            String imageName = imageNameBase + System.currentTimeMillis() + (counter > 0 ? "_" + counter : "") + imageNameExtension;
            file = new File(dir_news, imageName);
            counter++;
         } while (file.exists());

         try (InputStream inputStream = getContentResolver().openInputStream(imageUri);
              FileOutputStream outputStream = new FileOutputStream(file)) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
               outputStream.write(buffer, 0, bytesRead);
            }

            savedImagePath = file.getAbsolutePath();
            Log.d("ImageSave", "Image saved successfully at: " + savedImagePath);
         }
      } catch (SecurityException se) {
         Log.e("ImageSave", "Security exception when accessing storage", se);
      } catch (FileNotFoundException fnfe) {
         Log.e("ImageSave", "Image file not found", fnfe);
      } catch (IOException ioe) {
         Log.e("ImageSave", "Error occurred during image saving", ioe);
      }

      return savedImagePath;
   }

//   创建适配器
private class ImageAdapter extends BaseAdapter {

   @Override
   public int getCount() {
      return selectedImages.size();
   }

   @Override
   public Object getItem(int position) {
      return selectedImages.get(position);
   }

   @Override
   public long getItemId(int position) {
      return position;
   }

   @Override
   public View getView(final int position, View convertView, ViewGroup parent) {
      ViewHolder holder;
      if (convertView == null) {
         convertView = getLayoutInflater().inflate(R.layout.goods_photo_item, parent, false);
         holder = new ViewHolder();
         holder.imageView = convertView.findViewById(R.id.goods_photo);
         holder.closeImageView = convertView.findViewById(R.id.delete_photo);
         convertView.setTag(holder);
      } else {
         holder = (ViewHolder) convertView.getTag();
      }

      Uri imageUri = selectedImages.get(position);
      holder.imageView.setImageURI(imageUri);
      holder.closeImageView.setVisibility(View.VISIBLE);


      // 在这里直接设置关闭按钮的点击监听器
      holder.closeImageView.setOnClickListener(v -> {
         if (selectedImages.size() > position) { // 确保索引有效
            selectedImages.remove(position);
            adapter.notifyDataSetChanged();
         }
      });

      return convertView;
   }

   private class ViewHolder {
      ImageView imageView;
      ImageView closeImageView;
   }
}
}
